#include "convolution.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEBUG

/* typedef struct{
    
    IMGTYPE* ImgAry;
     int RowSize;;
     int ColSize;
    
} ImgStut;
typedef ImgStut*  pImgStut; */
IMGTYPE GetPixel(pImgStut img,pImgStut pattern, int y,int x){
    if(pattern)
        return *(img->ImgAry+((img->ColSize)*(y+pattern->RowSize/2+1)+(x+pattern->ColSize/2+1)));   
    else 
        return *(img->ImgAry+(y*img->ColSize+x));
}
IMGTYPE SetPixel(pImgStut img,pImgStut pattern ,int y,int x,IMGTYPE data){
    if(pattern)
        return *(img->ImgAry+((img->ColSize)*(y+pattern->RowSize/2+1)+(x+pattern->ColSize/2+1)))=data;   
    else 
        return *(img->ImgAry+(y*img->ColSize+x))=data;
    
    
    
}

void convolution(pImgStut Img,pImgStut pattern){
    pImgStut ResultImg;
    ResultImg=CreateImg(Img->RowSize,Img->ColSize);
    pImgStut expended;
    expended=CreateImg(Img->RowSize+2*(pattern->RowSize/2+1),Img->ColSize+2*(pattern->ColSize/2+1));
#ifdef DEBUG
PrintImg(expended);
#endif
    int x,y;

    for(y=0;y<Img->RowSize;y++){
        for(x=0;x<Img->ColSize;x++){
            SetPixel(expended,pattern,y,x,GetPixel(Img,NULL,y,x));
            
            
        }
        
        
    }
#ifdef DEBUG
PrintImg(expended);
#endif
    
    
    
    
}


pImgStut CreateImg(int ImgRowSize,int ImgColSize){
    //return the pointer of new img Struct with init size.
    pImgStut ImgToCreate=(pImgStut)malloc(sizeof(pImgStut));
    
    ImgToCreate->ImgAry=(char *)malloc(sizeof(IMGTYPE)*(ImgRowSize*ImgColSize));
    memset(ImgToCreate->ImgAry,0,sizeof(IMGTYPE)*(ImgRowSize*ImgColSize));
    ImgToCreate->RowSize=ImgRowSize;
    ImgToCreate->ColSize=ImgColSize;
    return ImgToCreate;
    
    
}

int PrintImg(pImgStut img){
	/*Print the image with boundary*/
	int x,y;
	/*upper boundary*/
	putchar(' ');
	for(x=0;x<img->ColSize;x++){
		putchar('-');
	}
		putchar('\n');
	
	for(y=0;y<img->RowSize;y++){
		/*left boundary*/
		putchar('|');
		
        for(x=0;x<img->ColSize;x++){
            //printf("%c",*img->ImgAry++?'#':' ');
            putchar((*img->ImgAry++)+'0');
            
        }
		/*right boundary*/
		putchar('|');
		
        putchar('\n');
        
    }
    putchar(' ');
	for(x=0;x<img->ColSize;x++)
		putchar('-');
	putchar('\n');
#ifdef DEBUG
printf("---Col:%d Row:%d---\n",img->ColSize,img->RowSize);
#endif
	return x*y;
	
}
